package cn.tedu._05weibo.controller;

import cn.tedu._05weibo.common.response.JsonResult;
import cn.tedu._05weibo.common.response.StatusCode;
import cn.tedu._05weibo.mapper.WeiboMapper;
import cn.tedu._05weibo.pojo.dto.WeiboDTO;
import cn.tedu._05weibo.pojo.entity.Weibo;
import cn.tedu._05weibo.pojo.vo.UserVO;
import cn.tedu._05weibo.pojo.vo.WeiboDetailVO;
import cn.tedu._05weibo.pojo.vo.WeiboIndexVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.yaml.snakeyaml.events.Event;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Validated
@Api(tags = "02.微博模块")
@RestController
@RequestMapping("/v1/weibo/")
public class WeiboController {
    @Autowired
    private WeiboMapper weiboMapper;

    /**
     * 1.发布微博功能
     */
    @ApiOperation(value = "发布微博功能")
    @PostMapping("insert")
    public JsonResult insert(@RequestBody WeiboDTO weiboDTO, @ApiIgnore HttpSession session) {
        UserVO userVO = (UserVO) session.getAttribute("user");
//        if (userVO == null) {
//            return  JsonResult.ok() ;
//        }//未登录
        Weibo weibo = new Weibo();
        BeanUtils.copyProperties(weiboDTO, weibo);
        weibo.setCreated(new Date());
        weibo.setUserId(userVO.getId());
        weiboMapper.insertWeibo(weibo);
        return JsonResult.ok();
    }

    /**
     * 2.微博首页列表功能
     */
    @ApiOperation(value = "微博首页列表")
    @GetMapping("selectIndex")
    public JsonResult selectIndex() {
        List<WeiboIndexVO> weiboIndexVOS=weiboMapper.selectIndex();
        return  JsonResult.ok(weiboIndexVOS);
    }

    /**
     * 3.微博详情页功能
     */

    @GetMapping("selectById")
    @ApiOperation(value = "微博详情页")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "id", value = "微博编号", required = true, example = "200", dataType = "int"),
            @ApiImplicitParam(name = "username", value = "用户名", required = true, dataType = "string")
    })
    public JsonResult selectById(@Range(min=200,max = 500,
            message = "微博编号必须在200~500之间")@RequestParam int id, String username) {
        if(id<0){
            throw new IllegalArgumentException("ID值无效");
        }
        //username参数仅仅是为了Knife4j中注解测试,没有任何其他作用.
        WeiboDetailVO weiboDetailVO = weiboMapper.selectById(id);
        return  JsonResult.ok(weiboDetailVO);
    }


}
